/**
 * Created by Administrator on 2017/9/20.
 */
angular.module('module.news')
    .controller('NewsListController', NewsListController);
NewsListController.$inject = ['$state', '$scope', '$localStorage', '$filter', 'NewsService'];
function NewsListController($state, $scope, $localStorage, $filter, NewsService) {

    var vm = this;
    if (!$localStorage[environmental + "shopid"]) {
        $localStorage.$reset();
        $state.go('login');
    }
    var shopid = $localStorage[environmental + "shopid"];
    vm.remainShow = remainShow;
    vm.getTableName = getTableName;
    vm.duration = duration;
    vm.audioPlay = audioPlay;
    vm.newsarry = [];
    var map = {};
    vm.dest = [];
    var list = {};
    vm.deslist = [];
    vm.firmNews = firmNews; // 点击确认消息
    vm.unHandle = unHandle;
    vm.newsarry = [];
    var myDate = new Date();
    var nowTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate() - 7, 0, 0, 0);
    var startTime = $filter('date')(nowTime, 'yyyy-MM-dd HH:mm:ss');
    var endTime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');

    NewsService.getNewsByShopId(shopid, 0, startTime, endTime).$promise.then(function (data) {
        vm.newsarry = data;
        newListF();
        doClient(newsNote, shopid);
    }, function (error) {
        vm.newsarry = [];
        doClient(newsNote, shopid);
    });

    // 获取消息
    function newsNote(topic, payload) {
        var message = JSON.parse(payload);
        var changebody = JSON.parse(message.body.body);
        var newsdetail = {
            callcontent: changebody.msg,
            createtime: message.headers.createtime,
            device: changebody.device,
            handleid: 0,
            handlename: null,
            handletime: null,
            modetype: message.headers.content_type,
            shopid: changebody.shopid,
            tableid: changebody.tableid,
        };
        vm.newsarry.push(newsdetail);
        newListF(true);
    }

    function newListF(tips) {
        for (var i = 0; i < vm.newsarry.length; i++) {
            var ai = vm.newsarry[i];
            if (!map[ai.tableid]) {
                map[ai.tableid] = [];
                if (tips) {
                    $scope.$apply(function () {
                        vm.dest.push({
                            tablename: "",
                            tableid: ai.tableid,
                            createtime: ai.createtime,
                            data: [ai]
                        });
                    })
                } else {
                    vm.dest.push({
                        tablename: "",
                        tableid: ai.tableid,
                        createtime: ai.createtime,
                        data: [ai]
                    });
                }
                map[ai.tableid].push(ai);
            } else {
                for (var j = 0; j < vm.dest.length; j++) {
                    var dj = vm.dest[j];
                    if (dj.tableid == ai.tableid) {
                        if (dj.data.indexOf(ai) == -1) {
                            if (tips) {
                                $scope.$apply(function () {
                                    dj.data.push(ai);
                                })
                            } else {
                                dj.data.push(ai);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }

    function remainShow() {
        $(".news_remain").show();
    }

    $(".news_remain").click(function () {
        $(".news_remain").hide();
    });

    function firmNews(newslist) {
        $("#newsgou" + newslist.tableid).attr('src', "images/newfinish.png");
        var newsdata = newslist.data;
        for (var i = 0; i < newsdata.length; i++) {
            var newsitem = newsdata[i];
            newsitem.handleid = 1;
        }
        NewsService.updateNews(newsdata, function (data) {
        }, function (error) {
        });
        delete map[newslist.tableid];
        var index = vm.dest.indexOf(newslist);
        if (index > -1) {
            vm.dest.splice(index, 1);
        }
    }

    // 获取已处理消息
    var middletime = "";

    function unHandle() {
        if (vm.deslist.length != 0) {
            starttime = middletime;
        }
        var endtime = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
        NewsService.getNewsByShopId(shopid, 1, starttime, endtime).$promise.then(function (data) {
            middletime = endtime;
            newsList(data);
            vm.deslist.sort(compare("handletime"));
        }, function (error) {
        })
    }

    // 数组反序
    function compare(property) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value2 - value1;
        }
    }

    // 已处理消息分组
    function newsList(item) {
        for (var i = 0; i < item.length; i++) {
            var ai = item[i];
            if (!list[ai.handletime]) {
                vm.deslist.push({
                    tableid: ai.tableid,
                    handletime: ai.handletime,
                    data: [ai]
                });
                list[ai.handletime] = ai;
            } else {
                for (var j = 0; j < vm.deslist.length; j++) {
                    var dj = vm.deslist[j];
                    if (dj.handletime == ai.handletime) {
                        dj.data.push(ai);
                        break;
                    }
                }
            }
        }
    }

    //通过桌台id获取桌台名称
    function getTableName(item) {
        NewsService.getTableByTableId(item.tableid).$promise.then(function (data) {
            if (data.createtime) {
                item.tablename = data.tablename;
            } else {
                item.tablename = "未知";
            }
        }, function (error) {
            console.log(error);
        });
    }

    //处理音频消息
    function duration(news) {
        fetchBlob(news.callcontent, function (blob) {
            playAmrBlob(blob, callback);
        });
        function callback(audioSrc) {
            news.audioSrc = audioSrc;
            var margin = Math.sqrt(audioSrc.buffer.duration) / 20;
            if (margin > 1) {
                margin = 1;
            }
            if (parseInt(audioSrc.buffer.duration / 60) > 0) {
                news.minute = parseInt(audioSrc.buffer.duration / 60);
            }
            news.second = parseInt(audioSrc.buffer.duration % 60);
            $(".audio_bac" + news.createtime).css({"margin-right": margin + "rem"});
        }
    }

    // 音频的播放和暂停
    var lastAudioSrc, lastNews, bac_time = null;
    function audioPlay(news) {
        if (lastAudioSrc && news.audioSrc != lastAudioSrc) {
            if (lastNews.isPlay) {
                lastAudioSrc.stop();//audio.play();// 这个就是播放
                NewsService.setStatus('buffer', null);
                lastNews.isPlay = false;
            }
        }
        lastAudioSrc = news.audioSrc;
        lastNews = news;
        if (lastAudioSrc !== null) {
            //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
            if (news.isPlay) {
                news.isPlay = false;
                $(".audio_bac" + news.createtime).removeClass("bac_active");
                lastAudioSrc.stop();// 这个就是暂停
                NewsService.setStatus('buffer', null);
            } else {
                clearTimeout(bac_time);
                news.isPlay = true;
                fetchBlob(news.callcontent, function (blob) {
                    playAmrBlob(blob, play);
                });
                function play(audioSrc) {
                    news.audioSrc = audioSrc;
                    $(".audio_bac").removeClass("bac_active");
                    $(".audio_bac" + news.createtime).addClass("bac_active");
                    audioSrc.start();// audio.play(); // 这个就是播放
                    NewsService.setStatus('buffer', audioSrc);
                    bac_time = setTimeout(function () {
                        $(".audio_bac" + news.createtime).removeClass("bac_active");
                        news.isPlay = false;
                        NewsService.setStatus('buffer', null);
                    }, lastAudioSrc.buffer.duration * 1000);
                    lastAudioSrc = audioSrc;
                }
            }
        }
    }
}